import { spawn } from "child_process";
import path from "path";

class ClientStart {
  protected binaryExe: any;
  protected binaryExeConfig: any;
  protected ARIA: any;
  protected accumulatedData: string;
  constructor() {
    this.binaryExe = path.resolve(__dirname, "bin", "aria2c.exe");
    this.binaryExeConfig = path.resolve(__dirname, "bin", "aria2.conf");
    this.ARIA = null;
    this.accumulatedData = "";
  }
  async start() {
    console.log("this.binaryExe ", this.binaryExe);
    console.log("this.binaryExeConfig ", this.binaryExeConfig);
    const configFile = `--conf-path=${this.binaryExeConfig}`;
    try {
      const startSpawn = () =>
        new Promise((resolve, reject) => {
          try {
            const s = spawn(this.binaryExe, [configFile]);
            console.log("is start aria")
            resolve(s);
          } catch (error) {
            reject(error);
          }
        });
      this.ARIA = await startSpawn();
      console.log("start aria", this.ARIA)
      // this.ARIA = await spawn(this.binaryExe, [configFile])
      return this.ARIA;
      this.outInfo();
    } catch (error) {
      console.log("client start error", error);
    }
  }
  protected outInfo() {
    if (this.ARIA) {
      // 进程输出
      this.ARIA.stdout.on("data", (data: any) => {
        this.accumulatedData += data.toString();
        if (this.accumulatedData.includes("ETA")) {
          console.info("process info", this.accumulatedData);
          this.accumulatedData = "";
        } else {
          console.log("---->outINFO 99%", data.toString());
        }
      });

      // 进程出错
      this.ARIA.stderr.on("data", (data: any) => {
        console.error(`process error: ${data}`);
      });

      //进程关闭事件
      this.ARIA.on("close", (code: any) => {
        console.warn("process close", code);
      });
    }
  }
}

// 打开二进制可执行软件aria
export const runEXE = async () => {
  const client = new ClientStart();
  await client.start();
  return client;
};
